package com.broada.apm.indicator.api.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.broada.apm.dao.LuaSettingsDao;
import com.broada.apm.indicator.api.LuaSettingsService;
import com.broada.apm.model.LuaSetting;
import com.broada.apm.model.LuaSettings;
import com.broada.apm.model.SettingItem;

public class LuaSettingsServiceImpl implements LuaSettingsService{
	
	@Autowired
	private LuaSettingsDao luaSettingsDao;
	
	@Override
	public void saveLuaSettings(LuaSettings settings) {
		List<SettingItem> items = settings.getItems();
		if(items != null && items.size() > 0){  //有配置项
			luaSettingsDao.deleteLuaSettingsByServiceId(settings.getServiceId());
			for(int i=0; i< settings.getItems().size(); i++){
				LuaSetting setting = new LuaSetting();
				setting.setServiceId(settings.getServiceId());
				setting.setL7Field(settings.getL7Field());
				setting.setThresType(settings.getThresType());
				setting.setFieldName(items.get(i).getFieldName());
				setting.setFieldCaption(items.get(i).getFieldCaption());
				setting.setPath(items.get(i).getPath());
				luaSettingsDao.saveLuaSettings(setting);
			}
		}else{    // 无配置项
			if(StringUtils.isBlank(settings.getL7Field()) && StringUtils.isNotBlank(settings.getServiceId())){
				luaSettingsDao.deleteLuaSettingsByServiceId(settings.getServiceId());
				return;  //无数据
			}else{
				luaSettingsDao.deleteLuaSettingsByServiceId(settings.getServiceId());
				LuaSetting setting = new LuaSetting();
				setting.setServiceId(settings.getServiceId());
				setting.setL7Field(setting.getL7Field());
				setting.setThresType(settings.getThresType());
				luaSettingsDao.saveLuaSettings(setting);
			}
		}
	}

	@Override
	public LuaSettings queryLuaSettings(String serviceId) {
		List<LuaSetting> setting = luaSettingsDao.queryLuaSettings(serviceId);
		if(setting == null){
			return null;
		}
		LuaSettings settings = new LuaSettings();
		settings.setServiceId(setting.get(0).getServiceId());
		settings.setThresType(setting.get(0).getThresType());
		settings.setL7Field(setting.get(0).getL7Field());
		List<SettingItem> items = new ArrayList<SettingItem>();
		for(LuaSetting set : setting){
			SettingItem item = new SettingItem();
			item.setFieldName(set.getFieldName());
			item.setFieldCaption(set.getFieldCaption());
			item.setPath(set.getPath());
			items.add(item);
		}
		settings.setItems(items);
		return settings;
	}
}
